﻿using System;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Controls;
using System.Windows.Printing;
using MedLink2011.Core;
using MedLink2011.Views.ClinicCharts.ChildWindows;
using MedLink2011.Views.ClinicCharts.Reports;
using MedLink2011.Web.Models;
using MedLink2011.Web.Services;
using System.Collections.ObjectModel;
using System.Windows;
using Telerik.Windows.Controls.GridView;
using RelayCommand = MedLink2011.Core.RelayCommand;
using System.Windows.Browser;
using MedLink2011.Controls;

namespace MedLink2011.Views.ClinicCharts.ViewModels
{
    public class Evaluation_SkinViewModel : PerformAsyncQueryBase // the AsyncQuery one inherits from ViewModel Base
    {
        public static MedLink2011Context _evaluation_SkinContext;
        private ObservableCollection<Evaluation_Skin> _evaluation_Skin;
        private MedLink2011Context _context;
        private EntityQuery<MedLink2011.Web.Models.ClinicChart> _clinicChartQuery;
        //
       public Evaluation_SkinViewModel()
        {
            if (!IsDesignTime)
            {
                _evaluation_SkinContext = new MedLink2011Context();
                IsBusy = true;
                WireCommands();
                LoadEvaluation_SkinAsync();
                LoadComboBoxData();
            }
        }
        
        #region "Load Current Evaluation_Skin"
        readonly int loadedClinicChart_Id = MedLink2011.Views.Patients.ViewModels.ClinicChartViewModel.DashLoad_PK;
        //readonly int loadedClinicChart_Id = 1;
        private void LoadEvaluation_SkinAsync()
         {
           if (!_evaluation_SkinContext.IsSubmitting)
            {
                if (loadedClinicChart_Id > 0)
                {
                    PerformAsyncQuery<Evaluation_Skin>(_evaluation_SkinContext, _evaluation_SkinContext.GetEvaluation_SkinsForClinicChartsQuery(loadedClinicChart_Id), Evaluation_SkinLoadedComplete);
                }
                else
                {
                    PerformAsyncQuery<Evaluation_Skin>(_evaluation_SkinContext, _evaluation_SkinContext.GetEvaluation_SkinsQuery(), Evaluation_SkinLoadedComplete); 
                }
            }
        }

        private EntitySet<Evaluation_Skin> _evaluation_SkinCollection;
        public EntitySet<Evaluation_Skin> Evaluation_SkinCollection
        {
            get { return _evaluation_SkinCollection; }
            set
            {
                _evaluation_SkinCollection = value;
                RaisePropertyChanged("Evaluation_SkinCollection");
            }
        }

        private Evaluation_Skin _currentEvaluation_Skin;
        public Evaluation_Skin CurrentEvaluation_Skin
        {
            get { return _currentEvaluation_Skin; }
            set
            {
                _currentEvaluation_Skin = value;
                RaisePropertyChanged("CurrentEvaluation_Skin");
            }
        }

        #endregion "Load Current Evaluation_Skin"

        #region Commands

        private void EnableCommands()
        {
            AddNewEvaluation_SkinCommand.IsEnabled = true;
            SaveEvaluation_SkinCommand.IsEnabled = true;
            DeleteEvaluation_SkinCommand.IsEnabled = true;
            PrintEvaluation_SkinCommand.IsEnabled = true;
            SearchEvaluation_SkinCommand.IsEnabled = true;
            SelectionChangedCommand.IsEnabled = true;
            RowLoadedCommand.IsEnabled = true;
            ShowChartDashboardCommand.IsEnabled = true;
           }

        private void WireCommands()
        {
            AddNewEvaluation_SkinCommand = new RelayCommand(AddEvaluation_Skin);
            SaveEvaluation_SkinCommand = new RelayCommand(SaveEvaluation_Skin);
            DeleteEvaluation_SkinCommand = new RelayCommand(DeleteEvaluation_Skin);
            PrintEvaluation_SkinCommand = new RelayCommand(PrintEvaluation_Skin);
            ShowChartDashboardCommand = new RelayCommand<object>(ShowChartDashboard);
            SearchEvaluation_SkinCommand = new RelayCommand<string>(SearchInEvaluation_Skin);
            SelectionChangedCommand = new RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs>(e =>
            {
                var element = e.OriginalSource as UIElement;
                var element2 = e.OriginalSource as Telerik.Windows.Controls.DataControl;

                if ((element2 != null) && (!_toDelete))
                {
                    var _theItem = element2.SelectedItem;
                    CurrentEvaluation_Skin = (Evaluation_Skin) _theItem;
            SelectedClinicChart =
                ClinicChartCollection.Where(c => c.ClinicChart_Id == CurrentEvaluation_Skin.ClinicChart_Id).SingleOrDefault();
              }
            });
            
            RowLoadedCommand = new RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs>( e =>
                {
                    if (e.Row is GridViewRow && !(e.Row is GridViewNewRow))
                    {
                        MedLink2011.Web.Models.Evaluation_Skin model = e.DataElement as MedLink2011.Web.Models.Evaluation_Skin;
                        var grid = new Grid();
                        var tb = new TextBlock
                               {
                               Text = string.Format(
			"Skin Wnl : {0} \r\n"+
			"Ecchymoses : {1} \r\n"+
			"Rash : {2} \r\n"+
			"Bullae : {3} \r\n"+
			"Pressure Ulcer Stage  1 : {4} \r\n"+
			"Pressure Ulcer Stage  2 : {5} \r\n"+
			"Pressure Ulcer Stage  3 : {6} \r\n"+
			"Pressure Ulcer Stage  4 : {7} \r\n"+
			"Other Skin Disease : {8} \r\n"+
			"Other Skin Disease Value : {9} \r\n"+
			"Evaluation Skin Notes : {10} \r\n",

			model.Skin_WNL,
			model.Ecchymoses,
			model.Rash,
			model.Bullae,
			model.Pressure_Ulcer_Stage_1,
			model.Pressure_Ulcer_Stage_2,
			model.Pressure_Ulcer_Stage_3,
			model.Pressure_Ulcer_Stage_4,
			model.Other_Skin_Disease,
			model.Other_Skin_Disease_Value,
			model.Evaluation_Skin_Notes
                     ),
                            Margin = new Thickness(3, 3, 3, 3),
                            Opacity = 0.8,
                            MaxWidth = 250,
                            FontSize = 10,
                            TextWrapping = TextWrapping.NoWrap
                                     };
                        grid.Children.Add(tb);
                        ToolTipService.SetToolTip(e.Row, grid);
                    }
                });
                
           }

        public RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs> RowLoadedCommand
        {
            get;
            private set;
        }

        public RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs> SelectionChangedCommand
        {
            get;
            private set;
        }

        public RelayCommand AddNewEvaluation_SkinCommand
        {
            get;
            private set;
        }
        public RelayCommand SaveEvaluation_SkinCommand
        {
            get;
            private set;
        }
        public RelayCommand DeleteEvaluation_SkinCommand
        {
            get;
            private set;
        }
        public RelayCommand PrintEvaluation_SkinCommand
        {
            get;
            private set;
        }

        public RelayCommand<object> ShowChartDashboardCommand
        {
            get;
            private set;
        }

        public RelayCommand<string>  SearchEvaluation_SkinCommand
        {
            get;
            private set;
        }

        #endregion Commands
        
        private void SearchInEvaluation_Skin( string searchText)
        {
            MessageBox.Show(searchText);
        }
        
        private void SaveEvaluation_Skin()
        {
            CurrentEvaluation_Skin.ClinicChart_Id = SelectedClinicChart.ClinicChart_Id;
            CurrentEvaluation_Skin.write_date = CurrentTime;
            CurrentEvaluation_Skin.write_uid = CurrentUser;
            _evaluation_SkinContext.SubmitChanges(p =>
            {
                if (p.HasError)
                {
                    p.MarkErrorAsHandled();
                    ErrorWindow.CreateNew(p.Error);
                }
                else
                {
                    MessageBox.Show("Evaluation_Skin se ha actualizado");
                    RaisePropertyChanged("Evaluation_SkinCollection");
                    RaisePropertyChanged("CurrentEvaluation_Skin");
                }
            }, null);
        }
        #region "Add New"
        //http://forums.silverlight.net/forums/p/193377/449256.aspx
        private void AddEvaluation_Skin()
        {

            MedLink2011.Web.Models.Evaluation_Skin evaluation_Skin = new MedLink2011.Web.Models.Evaluation_Skin();
            Evaluation_SkinsAddCW addNewWindow = new Evaluation_SkinsAddCW();
            addNewWindow.DataContext = evaluation_Skin;
            addNewWindow.Closed += (s, ee) =>
            {
                if (addNewWindow.DialogResult == true)
                {
                    evaluation_Skin.create_date = CurrentTime;
                    evaluation_Skin.write_date = CurrentTime;
                    evaluation_Skin.create_uid = CurrentUser;
                    evaluation_Skin.write_uid = CurrentUser;
                    
                    _evaluation_SkinContext.Evaluation_Skins.Add(evaluation_Skin);
                    _evaluation_SkinContext.SubmitChanges(p =>
                    {
                        if (p.HasError)
                        {
                            p.MarkErrorAsHandled();
                            ErrorWindow.CreateNew(p.Error);
                        }
                        else
                        {
                            MessageBox.Show("New Evaluation_Skin has been added");
                        }
                    }, null);
                }
            };
            addNewWindow.Show();
            addNewWindow.Closed += FrmClosedAdd;
        }


        void FrmClosedAdd(object sender, EventArgs e)
        {
            LoadEvaluation_SkinAsync();
        }
        #endregion "Add New"


        private static int _dashload_PK;
        public static int DashLoad_PK
        {
            get { return _dashload_PK; }
            set { _dashload_PK = value ; }
        }


        private void ShowChartDashboard(object selectedItem)
        {
            //
            string a = selectedItem.ToString();
            int i = a.IndexOf(":") + 1;
            a = a.Substring(i);
            int dashLoadPk;
            int.TryParse(a, out dashLoadPk);
            DashLoad_PK = dashLoadPk;
            Uri target = new Uri("/ClinicCharts/Pages/PatientsTitlePage?Evaluation_Skin_id=" + DashLoad_PK, UriKind.Relative);

   
            var _theItem = selectedItem;
            CurrentEvaluation_Skin = (Evaluation_Skin)_theItem;
            //NavigationService.Navigate(target);
            //var service = ((Page)((App)Application.Current).RootVisual).NavigationService;
            //if (service != null) service.Navigate(target);
        }



        private static int _current_Patient_id;
        public static int Current_Patient_id
        {
            get { return _current_Patient_id; }
            set { _current_Patient_id = value ; }
        }
        
        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                RaisePropertyChanged("IsBusy");
            }
        }
        public string CurrentTime
        {
            get
            {
                DateTime time = DateTime.Now;   
                const string format = "MMM ddd d HH:mm yyyy";  
                return (time.ToString(format));
            }
        }

        public string CurrentUser
        {
            get { return WebContext.Current.User.ToString() ; }
        }


        #region "LoadComboBoxData"

            
        public EntitySet<ClinicChart> ClinicChartCollection { get; set; }
        private ClinicChart _selectedClinicChart;
        public  ClinicChart SelectedClinicChart
        {
            get { return _selectedClinicChart; }
            set
            {
                _selectedClinicChart = value;
                RaisePropertyChanged("SelectedClinicChart");
            }
        }
        private long dtStart = 0;
        private long dtEnd = 0;
        void LoadComboBoxData()
        {
            dtStart = System.DateTime.Now.Ticks;
            
            //ClinicChart_IdComboBox
            _context = new MedLink2011Context();
            _clinicChartQuery = _context.GetClinicChartsQuery();
            _clinicChartQuery = _clinicChartQuery.OrderBy(e => e.ClinicChart_Id);
            PerformAsyncQuery<ClinicChart>(_context, _clinicChartQuery, ClinicChart_IdComboBoxLoaded);
            ClinicChartCollection = _context.ClinicCharts;
        }
        
        private void ClinicChart_IdComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<ClinicChart> e)
        {
            if (!e.HasError)
            {
                SelectedClinicChart =
                    ClinicChartCollection.Where(c => c.ClinicChart_Id == CurrentEvaluation_Skin.ClinicChart_Id).SingleOrDefault();
            }
        }


        private void Evaluation_SkinLoadedComplete(object sender, MedLink2011.Core.EntityResultsArgs<Evaluation_Skin> e)
        {
            IsBusy = false;
            if (!e.HasError)
            {
                Evaluation_SkinCollection = _evaluation_SkinContext.Evaluation_Skins;
                CurrentEvaluation_Skin = Evaluation_SkinCollection.FirstOrDefault();
                EnableCommands();
            SelectedClinicChart = ClinicChartCollection.Where(c => c.ClinicChart_Id == CurrentEvaluation_Skin.ClinicChart_Id).SingleOrDefault();

            }
            else
            {
                // notify user if there is any error
                //AppMessages.RaiseErrorMessage.Send(e.Error);
            }
        }

        private void AddNewForm_Closed(object sender, MedLink2011.Core.EntityResultsArgs<Evaluation_Skin> e)
        {
            if (!e.HasError)
            {
                
            }
        }


        #endregion "LoadComboBoxData"

        #region "Delete"

        private bool _toDelete=false;

        private void DeleteEvaluation_Skin()
        {
            _toDelete = true;
            var evaluation_SkinToDelete = CurrentEvaluation_Skin;
           if (evaluation_SkinToDelete != null)
                    {
                     var result = MessageBox.Show("Are you sure you wish to delete the Current Evaluation_Skin?", "Confirm Delete", MessageBoxButton.OKCancel);
                      if (result.Equals(MessageBoxResult.OK))
                        {
            _evaluation_SkinContext.Evaluation_Skins.Remove(evaluation_SkinToDelete);
            _evaluation_SkinContext.SubmitChanges(o =>
            {
                if (o.HasError)
                {
                    MessageBox.Show("Esta evaluation_Skin no se puede eliminar ya que existen datos que dependen de esta Evaluation_Skin.....", "Cancelado", MessageBoxButton.OKCancel);
                    o.MarkErrorAsHandled();
                    _evaluation_SkinContext.RejectChanges();
                }
                else
                {
                    MessageBox.Show("el registro de  evaluation_Skin ha sido eliminado exitosamente ... ");
                    //LoadEvaluation_SkinAsync();
                    RaisePropertyChanged("Evaluation_SkinCollection");
                    CurrentEvaluation_Skin = Evaluation_SkinCollection.FirstOrDefault();
                }
            }, null);
            }
       }
            _toDelete = false;
        }
        #endregion "Delete"
        
        #region "Print"
        
        private void PrintEvaluation_Skin()
        {
            if (CurrentEvaluation_Skin != null)
            {
                PrintDocument document = new PrintDocument();
                document.PrintPage += new System.EventHandler<PrintPageEventArgs>(document_PrintPage); // fires when every single page is going to print 
                document.EndPrint += new System.EventHandler<EndPrintEventArgs>(document_EndPrint); // when printing is completed
                string PrintQueue = "Evaluation_Skins_" + CurrentEvaluation_Skin.ToString(); // to show in the print queue
                document.Print(PrintQueue); //fires when printing has begun
            }
        }
        
        static void document_EndPrint(object sender, EndPrintEventArgs e)
        {
            if (e.Error != null)
            {
                ErrorWindow error = new ErrorWindow(e.Error.Message, e.Error.StackTrace);
            }
            else
                MessageBox.Show("Print Complete");
        }
        
        void document_PrintPage(object sender, PrintPageEventArgs e)
        {
            PrintDocument document = sender as PrintDocument;
            MedLink2011.Web.Models.Evaluation_Skin appt = CurrentEvaluation_Skin as MedLink2011.Web.Models.Evaluation_Skin;
            if (appt != null)
            {
                //e.HasMorePages = appt.ChildEntity != null && document.PrintedPageCount < appt.ChildEntity.Count;
                //if (document.PrintedPageCount > 0)
                //{
                // e.PageVisual = new ChildEntityFReport() { DataContext = appt.ChildEntity.ElementAt(document.PrintedPageCount - 1) };
                //}
                //else
                e.PageVisual = new Evaluation_SkinsFReport() { DataContext = appt };
            }
        }
       
        #endregion "Print"

    }


}

